#include <QCoreApplication>
#include <QString>
#include <QDebug>
QString encrypt(QString plainText, QString key);
QString decrypt(QString cipherText, QString key);
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //TEST CASE
    QString plainText = "ZJU optics engineering";
    QString key = "Lwzaze5514";
    QString cipherText, Text;
    cipherText = encrypt(plainText, key);
    qDebug() << cipherText;
    Text = decrypt(cipherText, key);
    qDebug() << Text;
    //ERROR CASE
    plainText = "ZJU optics engineering";
    key = "ZJU optics engineering111";
    Text = encrypt(plainText, key);
    qDebug() << Text;
    Text = decrypt(cipherText, key);
    qDebug() << Text;
    return a.exec();
}
QString encrypt(QString plainText, QString key)
{
    QByteArray p = plainText.toUtf8();
    QByteArray k = key.toUtf8();
    int pLen, kLen, pInt, kInt, T, rest, N;
    QByteArrayList pList, kList;
    bool ok = true;
    //* length fill:using repeated and left
    pLen = p.length();
    kLen = k.length();
    if (pLen < kLen)
        return "ERROR!";
    T = pLen / kLen;
    rest = pLen % kLen;
    k = k.repeated(T) + k.left(rest);
    //* to hexlist
    p = p.toHex(':');
    pList = p.split(':');
    k = k.toHex(':');
    kList = k.split(':');
    //* add together
    QString pCode;
    for (int i = 0; i < pLen; i++)
    {
        pInt = pList[i].toInt(&ok, 16);
        kInt = kList[i].toInt(&ok, 16);
        pInt += kInt;
        pCode += QString::number(pInt, 16);
    }
    return pCode;
}
QString decrypt(QString cipherText, QString key)
{
    QByteArray p = cipherText.toUtf8();
    QByteArray k = key.toUtf8();
    int pLen, kLen, pInt, kInt, T, rest, N;
    QByteArrayList pList, kList;
    bool ok = true;
    //* length fill:using repeated and left
    pLen = p.length() / 2;
    kLen = k.length();
    if (pLen < kLen)
        return "ERROR!";
    T = pLen / kLen;
    rest = pLen % kLen;
    k = k.repeated(T) + k.left(rest);
    //* to hexlist
    for (int i = 2; i < p.length(); i = i + 3)
        p.insert(i, ":");
    pList = p.split(':');
    k = k.toHex(':');
    kList = k.split(':');
    //* minus together
    QString PlainHex;
    for (int i = 0; i < pLen; i++)
    {
        pInt = pList[i].toInt(&ok, 16);
        kInt = kList[i].toInt(&ok, 16);
        pInt -= kInt;
        PlainHex += QString::number(pInt, 16);
    }
    QByteArray temp = PlainHex.toLocal8Bit();
    QByteArray Plain = QByteArray::fromHex(temp);
    return Plain;
}
